package org.mozhu.mboot.core.security.jasypt;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.env.PropertiesPropertySource;
import org.springframework.util.StringUtils;

import java.util.Properties;

@Slf4j
public class JasyptContextInitializer implements ApplicationContextInitializer<ConfigurableApplicationContext> {

    public static final String JASYPT_ENCRYPTOR_PASSWORD = "jasypt.encryptor.password";

    @Override
    public void initialize(ConfigurableApplicationContext applicationContext) {
        ConfigurableEnvironment environment = applicationContext.getEnvironment();
        String property = environment.getProperty(JASYPT_ENCRYPTOR_PASSWORD);
        if (StringUtils.isEmpty(property)) {
            StandardConsoleInputPropertiesCollector standardConsoleInputPropertiesCollector = new StandardConsoleInputPropertiesCollector();
            standardConsoleInputPropertiesCollector.add(StandardConsoleInputProperty.builder().key(JASYPT_ENCRYPTOR_PASSWORD).tips("秘钥").build());
            Properties properties = standardConsoleInputPropertiesCollector.collect();
            environment.getPropertySources().addLast(new PropertiesPropertySource("jasyptProperties", properties));
            log.info("Add jasypt properties into environment");
        }
    }
}
